<?php
/**
 * Cart API Handler - Unified cart operations
 */
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    $user_id = $_SESSION['user_id'];
    $product_id = (int)($input['product_id'] ?? 0);
    $quantity = (int)($input['quantity'] ?? 1);
    
    switch($action) {
        case 'add':
            if ($product_id <= 0 || $quantity <= 0) {
                echo json_encode(['success' => false, 'message' => 'Invalid data']);
                exit;
            }
            $product = getProductById($pdo, $product_id);
            if (!$product || (isset($product['is_active']) && !$product['is_active'])) {
                echo json_encode(['success' => false, 'message' => 'Product unavailable']);
                exit;
            }
            $result = addToCart($pdo, $user_id, $product_id, $quantity);
            echo json_encode([
                'success' => $result,
                'message' => $result ? 'Added to cart' : 'Failed',
                'cart_count' => count(getCartItems($pdo, $user_id))
            ]);
            break;
            
        case 'remove':
            if ($product_id <= 0) {
                echo json_encode(['success' => false, 'message' => 'Invalid data']);
                exit;
            }
            $result = removeFromCart($pdo, $user_id, $product_id);
            $cart_items = getCartItems($pdo, $user_id);
            echo json_encode([
                'success' => $result,
                'message' => $result ? 'Removed from cart' : 'Failed',
                'cart_count' => count($cart_items),
                'cart_total' => getCartTotal($pdo, $user_id)
            ]);
            break;
            
        case 'update':
            if ($product_id <= 0) {
                echo json_encode(['success' => false, 'message' => 'Invalid data']);
                exit;
            }
            $product = getProductById($pdo, $product_id);
            if ($quantity > 0 && $product['stock_quantity'] < $quantity) {
                echo json_encode(['success' => false, 'message' => 'Insufficient stock']);
                exit;
            }
            $result = updateCartQuantity($pdo, $user_id, $product_id, $quantity);
            echo json_encode([
                'success' => $result,
                'message' => $result ? 'Updated' : 'Failed',
                'cart_total' => getCartTotal($pdo, $user_id)
            ]);
            break;
            
        case 'count':
            echo json_encode(['count' => count(getCartItems($pdo, $user_id))]);
            break;
            
        default:
            echo json_encode(['success' => false, 'message' => 'Invalid action']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}

